package com.web.exiaodao.remote.service.impl;

import com.alibaba.fastjson.JSON;
import com.web.exiaodao.business.constant.JConstant;
import com.web.exiaodao.business.entity.CheckInTable;
import com.web.exiaodao.business.entity.MakeMoneyTable;
import com.web.exiaodao.business.repository.CheckInTableRepository;
import com.web.exiaodao.business.repository.MakeMoneyTableRepository;
import com.web.exiaodao.remote.service.ApiCheckInTableService;
import com.web.exiaodao.remote.service.ApiConfigurationTableService;
import com.web.exiaodao.remote.service.ApiMakeMoneyTableService;
import com.web.exiaodao.remote.vo.CheckInTableVo;
import com.web.exiaodao.remote.vo.MakeMoneyTableVo;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.service.impl.BaseService;
import com.web.webstart.base.util.DateUtils;
import com.web.webstart.base.util.XaUtil;
import com.web.webstart.base.util.jpa.DynamicSpecifications;
import com.web.webstart.base.util.jpa.SearchFilter;
import com.web.webstart.base.util.jpa.SearchFilter.Operator;
import com.web.webstart.base.util.result.XaResult;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: zhangl
 * @times: 2015-5-15下午06:46:35
 * 类的说明：前端APICheckInTable接口实现类
 **/
@Service("ApiCheckInTableService")
@Transactional(readOnly = false)
public class ApiCheckInTableServiceImpl extends BaseService<CheckInTable> implements ApiCheckInTableService{

	private static final Logger LOGGER = Logger.getLogger(ApiCheckInTableServiceImpl.class);

	@Autowired
	CheckInTableRepository checkInTableRepository;
    @Autowired
    MakeMoneyTableRepository makeMoneyTableRepository;
    @Autowired
    ApiConfigurationTableService configurationTableService;
    @Autowired
    ApiMakeMoneyTableService makeMoneyTableService;

	@Override
	public XaResult<CheckInTableVo> findOne(Long tId) throws BusinessException {
		CheckInTable obj = checkInTableRepository.findByIdAndStatusNot(tId,XaConstant.Status.delete);
		XaResult<CheckInTableVo> xr = new XaResult<CheckInTableVo>();
		if (XaUtil.isNotEmpty(obj)) {
			xr.setObject(JSON.parseObject(JSON.toJSONString(obj),CheckInTableVo.class));
			xr.getObject().setId(obj.getId());
			LOGGER.info("查询单个实体----->CheckInTable");
		} else {
			xr.error(XaConstant.Message.object_not_find);
			LOGGER.info(XaConstant.Message.object_not_find);
		}
		return xr;
	}

	@Override
	public XaResult<List<CheckInTableVo>> findListNEStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable)
			throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示非删除的所有数据
			status = XaConstant.Status.delete;
		}
		filters.put("status", new SearchFilter("status", Operator.NE, status));
		Page<CheckInTable> page = checkInTableRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), CheckInTable.class), pageable);
		XaResult<List<CheckInTableVo>> xr = new XaResult<List<CheckInTableVo>>();
		xr.setObject(JSON.parseArray(JSON.toJSONString(page.getContent()), CheckInTableVo.class));
		for(int i=0;i<page.getContent().size();i++){
			xr.getObject().get(i).setId(page.getContent().get(i).getId());
		}
		return xr;
	}

	@Override
	public XaResult<List<CheckInTableVo>> findListEQStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable)
			throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示正常数据
			status = XaConstant.Status.valid;
		}
		filters.put("status", new SearchFilter("status", Operator.EQ, status));
		Page<CheckInTable> page = checkInTableRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), CheckInTable.class), pageable);
		XaResult<List<CheckInTableVo>> xr = new XaResult<List<CheckInTableVo>>();
		xr.setObject(JSON.parseArray(JSON.toJSONString(page.getContent()), CheckInTableVo.class));
		for(int i=0;i<page.getContent().size();i++){
			xr.getObject().get(i).setId(page.getContent().get(i).getId());
		}
		return xr;
	}

	@Override
	public XaResult<CheckInTableVo> multiOperate(String modelIds,
			Integer status) throws BusinessException {
		XaResult<CheckInTableVo> xr = new XaResult<CheckInTableVo>();
		if(status == null){
			status = XaConstant.Status.delete;
		}
		if(modelIds != null){
			String[] ids = modelIds.split(",");
			for(String id : ids){
				CheckInTable obj = checkInTableRepository.findByIdAndStatusNot(Long.parseLong(id),status);
				if (XaUtil.isNotEmpty(obj)) {
					obj.setStatus(status);
					obj = checkInTableRepository.save(obj);
					xr.setObject(JSON.parseObject(JSON.toJSONString(obj), CheckInTableVo.class));
					xr.getObject().setId(obj.getId());
				}
			}
		}
		LOGGER.info("更改数据状态----->CheckInTable");
		return xr;
	}

	@Transactional
	@Override
	public XaResult<CheckInTableVo> createModel(CheckInTable model)
			throws BusinessException {
		XaResult<CheckInTableVo> xr = new XaResult<CheckInTableVo>();
        //1:签到表添加一条记录
		model.setCheck_Count(model.getCheck_Count() + 1);
		CheckInTable obj = checkInTableRepository.save(model);
		xr.setObject(JSON.parseObject(JSON.toJSONString(obj), CheckInTableVo.class));
		xr.getObject().setId(obj.getId());
        LOGGER.info("新增数据成功----->CheckInTable");

        //2:签到赚到的亲和币 规则
        XaResult<Integer>  todayRs = configurationTableService.signMoneyByCheckCount((int)(model.getCheck_Count().longValue()));
        if (todayRs == null || todayRs.getObject() == null) {
            xr.error(todayRs.getMessage());
			return xr;
        }

        //3:赚钱表添加一条数据
        XaResult<MakeMoneyTable> makeMoneyXR = makeMoneyTableService.saveMakeMoneyRecord(model.getUserId(), JConstant.ConsumeOrMakeMoney.MakeMoney, todayRs.getObject() , JConstant.IntegralTypeEnum.SING.getIndex());
        xr.getObject().setMakeMoneyTableVo(JSON.parseObject(JSON.toJSONString(makeMoneyXR.getObject()), MakeMoneyTableVo.class));

		//4:明日签到应该获取的亲币数
		XaResult<Integer> tomorrowXR = configurationTableService.signMoneyByCheckCount((int)(model.getCheck_Count().longValue())+1);
		xr.getObject().setSign_coin(tomorrowXR.getObject());

		//5: 获取今日签可以获取的最低亲币数量
		int signCoinMin = configurationTableService.signMoneyByCheckCount(1).getObject();
		xr.getObject().setSignCoinMin(signCoinMin);

		return xr;
	}


    @Override
	public XaResult<CheckInTableVo> updateModel(CheckInTable model)
			throws BusinessException {
		CheckInTable obj = checkInTableRepository.findOne(model.getId());
		XaResult<CheckInTableVo> xr = new XaResult<CheckInTableVo>();
		if (XaUtil.isNotEmpty(obj)) {
					obj.setUserId(XaUtil.isNotEmpty(model.getUserId()) ? model.getUserId() : obj.getUserId());
					obj.setCheckIn_DateTime(XaUtil.isNotEmpty(model.getCheckIn_DateTime()) ? model.getCheckIn_DateTime() : obj.getCheckIn_DateTime());
					obj.setCheck_Count(XaUtil.isNotEmpty(model.getCheck_Count()) ? model.getCheck_Count() : obj.getCheck_Count());
				obj = checkInTableRepository.save(obj);
			xr.setObject(JSON.parseObject(JSON.toJSONString(obj), CheckInTableVo.class));
			xr.getObject().setId(obj.getId());
		} else {
			xr.error(XaConstant.Message.object_not_find);
		}
		LOGGER.info("编辑数据成功----->CheckInTable");
		return xr;
	}

	@Override
	public XaResult<CheckInTableVo> findLastOne(long userId) throws BusinessException {
		XaResult<CheckInTableVo> xr = new XaResult<>();
		Map<String, SearchFilter> filters = new HashMap<>();
		filters.put("status", new SearchFilter("status", Operator.NE, XaConstant.Status.delete));
		filters.put("userId", new SearchFilter("userId", Operator.EQ, userId));
		String nowDate = DateUtils.getToday(DateUtils.YYYYMMDD);//yyyy-MM-dd   yyyy-MM-dd HH:mm:ss
        String startDate = nowDate + " " + "00:00:00";
        String endDate   = nowDate + " " + "23:59:59";
		filters.put("checkIn_DateTime", new SearchFilter("checkIn_DateTime", Operator.BETWEEN, startDate + "," + endDate));
		List<CheckInTable> entitys = checkInTableRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), CheckInTable.class), new Sort(
				new Sort.Order[]{
						new Sort.Order(Sort.Direction.DESC, "createTime"),
						new Sort.Order(Sort.Direction.DESC, "id")
				}));
		if (entitys == null || entitys.size() == 0) {
			xr.error("今天还没签到");
            xr.setCode(XaConstant.Code.success);
            //今天还没签到:返回今日签到可以获取的亲币
            CheckInTableVo tempVo = new CheckInTableVo();
            long times = this.calculateCheckTimesYesterday(userId).getObject().longValue();
            XaResult<Integer>  xaResult = configurationTableService.signMoneyByCheckCount((int)times+1);
            tempVo.setSign_coin(xaResult.getObject());
            //连续签到的次数
            tempVo.setCheck_Count(times);
            tempVo.setUserId(userId);
			tempVo.setSignCoinNote("今天还没签到获取,返回今天签到应该获取的亲币:" + xaResult.getObject());
            xr.setObject(tempVo);
		} else {
		    //今天已经签到:返回明天签到可以获取的亲币
            CheckInTableVo tempVo = JSON.parseObject(JSON.toJSONString(entitys.get(0)), CheckInTableVo.class);
            XaResult<Integer>  xaResult = configurationTableService.signMoneyByCheckCount((int)((tempVo.getCheck_Count().longValue()+1)));
            tempVo.setSign_coin(xaResult.getObject());
			tempVo.setSignCoinNote("今天已经签到,返回明天签到可以获取的亲币:" + xaResult.getObject());
			xr.setObject(tempVo);
			xr.getObject().setId(entitys.get(0).getId());
			LOGGER.info("查询单个实体----->CheckInTable");
		}
		//获取今日签可以获取的最低亲币数量
		int signCoinMin = configurationTableService.signMoneyByCheckCount(1).getObject();
		xr.getObject().setSignCoinMin(signCoinMin);
		return xr;
	}

    /**
     * @Description: 计算截止昨天连续签到的次数
     * @author duandazhi
     * @date 2016/11/9 下午12:50
     * @param userId long 用户id
     * @return 如果昨天没有签到信息,就返回0;如果昨天签到了就返回昨天的签到数
     * @throws BusinessException
     */
    @Override
    public XaResult<Long> calculateCheckTimesYesterday(long userId) throws BusinessException {
        XaResult<Long> xr = new XaResult<>();
        String sql = "SELECT id, check_in_date_time, check_count, user_id FROM tb_xa_checkintable WHERE status <> 3 AND DATEDIFF(CURDATE(),check_in_date_time) = 1 AND user_id = " + userId + " ORDER BY id DESC LIMIT 1";
        Long diff = Long.valueOf(0);
        List<Object[]> objs = this.query(sql, null, null);
        for (int i = 0; objs != null &&  i < objs.size(); ++i) {
            CheckInTableVo vo = new CheckInTableVo();
            vo.setId(Long.parseLong(objs.get(i)[0].toString()));
            vo.setCheckIn_DateTime((String) objs.get(i)[1]);
            vo.setCheck_Count(Long.parseLong(objs.get(i)[2].toString()));
            vo.setUserId(Long.parseLong(objs.get(i)[3].toString()));
            diff =  vo.getCheck_Count();
            break;
        }
        xr.setObject(diff);
        return xr;
    }
}
